<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let arr = [
        { id: 1, name: '部门1', pid: 0 },
        { id: 2, name: '部门2', pid: 1 },
        { id: 3, name: '部门3', pid: 1 },
        { id: 4, name: '部门4', pid: 3 },
        { id: 5, name: '部门5', pid: 4 },
      ]
      function listTotree(arr, pid = 0) {
        const tree = []
        arr.forEach((item) => {
          if (item.pid === pid) {
            tree.push(item)
            const children = listTotree(arr, item.id)
            if (children.length > 0) {
              item.children = children
            }
          }
        })
        return tree
      }
        console.log(listTotree(arr))

    </script>
  </body>
</html>
